package grpc_server

import (
	"net"
	"os"
	"time"

	"google.golang.org/grpc/keepalive"

	"code.byted.org/bytertc/whiteboard_server/biz/rts"

	"code.byted.org/bytertc/whiteboard_server/biz/api/pb/wb_pb"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
)

type GrpcServer struct {
	addr string
	lis  net.Listener
	srv  *grpc.Server
}

func NewServer(addr string, rtsAdapter rts.Adapter, rtsManager rts.Manager) (*GrpcServer, error) {
	err := os.RemoveAll(addr)
	if err != nil {
		return nil, errors.Wrap(err, "remove sock error")
	}
	err = os.MkdirAll("/tmp/whiteboard", os.ModePerm)
	if err != nil {
		return nil, errors.Wrap(err, "mkdir error")
	}
	lis, err := net.Listen("unix", addr)
	if err != nil {
		return nil, errors.Wrap(err, "listen sock error")
	}
	srv := grpc.NewServer(
		grpc.KeepaliveParams(keepalive.ServerParameters{
			Time:    2 * time.Minute,
			Timeout: 2 * time.Minute,
		}),
		grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
			MinTime:             5 * time.Minute,
			PermitWithoutStream: true,
		}),
	)
	wb_pb.RegisterWhiteboardServer(srv, NewHandler(rtsAdapter, rtsManager))
	return &GrpcServer{
		addr: addr,
		lis:  lis,
		srv:  srv,
	}, nil
}

func (gs *GrpcServer) Addr() string {
	return gs.addr
}

func (gs *GrpcServer) Run() error {
	return gs.srv.Serve(gs.lis)
}
